﻿using SharpDX.XAudio2;
using System;
using System.Linq;
using System.Collections.Generic;

namespace MikadoShooter
{
    public class SoundPlayer : IDisposable
    {
        private readonly XAudio2 xaudio;
        private readonly MasteringVoice masteringVoice;
        private Dictionary<eSoundname, AudioCache> sounds;

        public SoundPlayer()
        {
            sounds = new Dictionary<eSoundname, AudioCache>();
            xaudio = new XAudio2();
            masteringVoice = new MasteringVoice(xaudio);
        }

        public void InitSoundFile()
        {
            SoundFile soundFile = SoundIO.LoadSoundXML();

            for (int i = 0; i < Enum.GetNames(typeof (eSoundname)).Length; i++)
            {
                LoadSound((eSoundname)i, ref sounds, soundFile);
            }
        }

        private static void LoadSound(eSoundname soundname, ref Dictionary<eSoundname, AudioCache> soundsDictionary, SoundFile soundFile)
        {
            SoundIO.LoadSound(soundname, ref soundsDictionary, soundFile.SoundElements.FirstOrDefault(x => x.Name == soundname.ToString().ToLower()), soundFile.Key, soundFile.IV);
        }

        public void PlaySound(eSoundname soundname)
        {
            if (!sounds.ContainsKey(soundname)) 
                return;

            using (SourceVoice sourceVoice = new SourceVoice(xaudio, sounds[soundname].Format))
            {
                sourceVoice.SubmitSourceBuffer(new AudioBuffer
                {
                    Stream = sounds[soundname].DataStream,
                    AudioBytes = sounds[soundname].Length
                }, sounds[soundname].DecodedPacketsInfo);

                sourceVoice.Start();
            }
        }

        public void Dispose()
        {
            if (sounds != null && sounds.Count > 0)
                sounds.Clear();

            if (masteringVoice != null)
                masteringVoice.Dispose();

            if (xaudio != null)
                xaudio.Dispose();
        }
    }
}